package db;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import basics.Dataset;
import basics.DatasetItem;
import basics.DenseVector;
import basics.SparseVector;
import basics.Vector;

public class TextFileHandler {

	public enum LabelPosition {
		FirstCol, LastCol, None
	}

	public static Dataset<Vector,Integer> read(String filename, String sep, LabelPosition l, boolean sparse, String innerSep) {
		Dataset<Vector,Integer> ds = new Dataset<Vector,Integer>();
		try {
			BufferedReader bi = new BufferedReader(new FileReader(new File(filename)));
			String line;
			String[] s;
			while ((line = bi.readLine()) != null && line.length() > 0) {
				s = line.split(sep);
				int start = 0, end = s.length;
				DatasetItem<Vector,Integer> item = new DatasetItem<Vector,Integer>();
				if (l == LabelPosition.FirstCol) {
					item.setValue(utils.Converter.parseSignedInt(s[start]));
					start++;
				} else if (l == LabelPosition.LastCol) {
					item.setValue(Integer.parseInt(s[end - 1]));
					end--;
				}
				item.setKey(sparse ? new SparseVector(end - start) : new DenseVector(end - start));
				for (int i = 0; i < end - start; i++) {
					int index = i;
					String val;
					if (innerSep.length() > 0) {
						String[] a = s[start + i].split(innerSep);
						index = Integer.parseInt(a[0]) - start;
						val = a[1];
					} else {
						val = s[i + start];
					}
					item.getKey().set(Double.parseDouble(val), i);
				}
				ds.add(item);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return ds;
	}
}
